<?php
namespace app\api\controller;

use think\Controller;
use think\Session;

/**
 * 通用上传接口
 * Class Upload
 * @package app\api\controller
 */
class Upload extends Controller
{
    protected function _initialize()
    {
        parent::_initialize();

    /*    if ( !Session::has('user')) {
            $result = [
                'error'   => 1,
                'message' => '未登录'
            ];
            echo json_encode($result);exit;
        }*/
    }

    /**
     * 通用图片上传接口
     * @return \think\response\Json
     */
    public function upload()
    {
        $config = [
            'size' => 2097152,
            'ext'  => 'jpg,gif,png,bmp,txt,zip'
        ];
        $file = $this->request->file('file');
        $upload_path = str_replace('\\', '/', ROOT_PATH . 'public/uploads');
        $save_path   = '/uploads/';
        $info        = $file->validate($config)->move($upload_path);

        if ($info) {
            $result = [
                'error' => 0,
                'url'   => str_replace('\\', '/', $save_path . $info->getSaveName())
            ];
        } else {
            $result = [
                'error'   => 1,
                'message' => $file->getError()
            ];
        }

        return json($result);
    }


    /**
     * @return \think\response\Json
     * base64位上传图片
     */
    public function uploadBase64()
    {
        $base64_image = str_replace(' ', '+', input('file'));
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image, $result)){
            //匹配成功
            $config = ["jpg","png","jpeg","gif"];
            if(in_array($result[2],$config)){
                $image_name = uniqid().'.'.$result[2];
                $upload_path = str_replace('\\', '/', ROOT_PATH . 'public');
                $save_path   = '/uploads/'.date('Ymd',time()).'/';
                if(!file_exists($upload_path.$save_path)){
                    mkdir($upload_path.$save_path,0777);
                }
                $image_file = $upload_path.$save_path.$image_name;
                //服务器文件存储路径
                if (file_put_contents($image_file, base64_decode(str_replace($result[1], '', $base64_image)))){
                    $result = [
                        'error' => 0,
                        'url'   => str_replace('\\', '/', $save_path.$image_name)
                    ];
                }else{
                    $result = [
                        'error'   => 1,
                        'message' => '存储失败'
                    ];
                }
            }else{
                $result = [
                    'error'   => 1,
                    'message' => "文件格式错误"
                ];
            }
        }else{
            $result = [
                'error'   => 1,
                'message' => "未知错误"
            ];
        }
        return json($result);
    }


}